<?php
/**
 * 343登陆
 */

namespace app\weapp\module\user;

use app\common\InstanceTrait;
use app\common\Redis;
use app\common\Uuid;
use app\core\user\UserModel;
use app\polymerize\tool\service\SMS;
use const app\polymerize\user\module\user\_MSG_ERROR_ACCOUNT;
use const app\polymerize\user\module\user\_MSG_NOT_ALLOWED_METHOD;
use const app\polymerize\user\module\user\_MSG_SYSTEM_SUCCESS;
use const app\polymerize\user\module\user\_TEL_CODE_LOGIN;

class LoginTel
{
    use InstanceTrait;

    /*
     * 更新
     */
    public function loginTel($post, $sys)
    {
        $result = UserModel::getInstance()->getUserByTel($post["tel"], $sys);

        if ($result["code"] != _MSG_SYSTEM_SUCCESS) {
            return ['code' => _MSG_ERROR_ACCOUNT, 'msg' => $result["msg"]];
        }
        $code = Uuid::getInstance()->makeTelCode(4);    // 验证码
        $codeTemp = Redis::getInstance()->redisGet(_TEL_CODE_LOGIN . $post["tel"]);

        $times = 1;
        $ttl = 60 * 10;
        if ($codeTemp["code"] == _MSG_SYSTEM_SUCCESS) {
            if ($codeTemp["data"]["times"] == 5) {    // 五次操作暂停接口
                return ['code' => _MSG_NOT_ALLOWED_METHOD, 'msg' => '操作次数过多，请一小时后重试'];
            }

            if (time() - $codeTemp["data"]["stamp"] < 1 * 60) {
                return ['code' => _MSG_NOT_ALLOWED_METHOD, 'msg' => '操作过快，一分钟后再试'];
            }

            $times = $codeTemp["data"]["times"] + 1;
            if ($times == 5) {
                $ttl = 60 * 60;
            }
        }

        Redis::getInstance()->redisSet(
            _TEL_CODE_LOGIN . $post["tel"],
            [
            "code" => $code,
            "times" => $times,
            "stamp" => time()
            ],
            $ttl
        );

        $result = SMS::getInstance()->sendCode($post["tel"], $code, $sys);
        if ($result["code"] != _MSG_SYSTEM_SUCCESS) {
            return ['code' => $result["code"], 'msg' => $result["msg"]];
        }

        return ['code' => 0, 'msg' => '成功'];
    }
}
